<template>
  <div>
    <component
      v-for="control in controls"
      :is="control.RenderComponent"
      :key="control.key"
      :item="control.item"
      :models="models"
      :readonly="formReadOnly"
      :datas="datas"
      :formDataChange="formDataChange"
      :options="options"
      :flowInfo="flowInfo"
      :flowConfig="flowConfig"
      :defKey="defKey"
      :taskId="taskId"
      :appName="appName"
      :defid="defid"
      :showNextNode="showNextNode"
      :showNextAssignees="showNextAssignees"
      :oneLegKicking="oneLegKicking"
      @change="change"
      ref='itemRefs'
    />
  </div>
</template>

<script>
import { getControl } from '../../mobile/controls'

export default {
  props: {
    pageConfig: {
      type: Object,
      default: () => ({
        "children": [],
        "config": {
          "labelWidth": 100,
          "labelPosition": "right",
          "size": "small"
        }
      })
    },
    models: Object,
    datas: Object,
    options: Object,
    flowInfo: Object,
    flowConfig: Object,
    defKey: String,
    taskId: String,
    defid: String,
    appName: Object,
    formDataChange: Object,
    formReadOnly: Boolean,
    showNextNode: Boolean,
    showNextAssignees: Boolean,
    oneLegKicking: Boolean
  },
  computed: {
    controls () {
      let { children } = this.pageConfig
      if (!children || children.length === 0) {
        return []
      }

      return children.map(item => ({
        key: item.key,
        item,
        RenderComponent: getControl(item.type)
      }))
    }
  },
  methods: {
    change(){
      this.$emit("change", this.getValue())
    },
    getValue () {
      let value = {}
      this.$refs.itemRefs && this.$refs.itemRefs.forEach(item => {
        if (item.getValue) {
          Object.assign(value, item.getValue())
        }
      })

      return value
    },
    setValue (val) {
      this.$refs.itemRefs && this.$refs.itemRefs.forEach(item => {
        if (item.setValue) {
          item.setValue(val)
        }
      })
    },
    validate () {
      const { itemRefs } = this.$refs
      if (!itemRefs) {
        return true
      }

      let ret = true
      itemRefs.forEach(item => {
        if (item.validate && item.validate() === false) {
          ret = false
        }
      })

      return ret
    }
  }
}
</script>
